require 'esi/machine'

module ESI
  class Parser < ESI::ParserMachine
    # Provides a stream like interface to a single parameter block
    class StreamCallBack
      def initialize(callback)
        @callback = callback
      end
      def << (output) 
        @callback.call( output )
      end
    end
    attr_accessor :esi_tag, :output, :depth

    def initialize( options = {} )
      super()
      @data = nil
      @prev_buffer = ""
      @start_tag = nil # call back for when we encounter a start tag
      @end_tag = nil # call back for when we encounter an end tag
      @esi_tag = nil # the current active esi tag
      @output = nil
      @depth = options[:depth] || 0 # used to track the depth of requests include tags should be initialized with this depth
    end

    def start_tag_handler(&block)
      @start_tag = block
    end

    def end_tag_handler(&block)
      @end_tag = block
    end

    def output_handler(&block)
      @output = StreamCallBack.new(block)
    end

  private
    def stream_buffer(string)
      if @esi_tag
        @esi_tag.buffer( @output, string )# unless string.strip.empty?
      else
        @output << string
      end
    end

  end
end
